import React from 'react';
import { inject, observer } from 'mobx-react';
import { Modal, Tooltip, message, Table } from 'antd';
import { WeaTableEditable, WeaRichText, WeaSearchGroup, WeaLocaleProvider, WeaTable } from 'ecCom';
import SearchGroupBorderLeft from '../SearchGroupBorderLeft';
import PlanDetail from './PlanDetail';
import * as Util from '../../../util/Util';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
const getUserLanguage = WeaLocaleProvider.getUserLanguage;
@inject('planReportViewStore')
@observer
export default class LastMonthWorkSummary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detailContent: '',
    };

    this.store = this.props.planReportViewStore;
    this.refreshKey = new Date().getTime()
  }



  willAdd = (datas, addData) => {
    datas.pop();
    this.store.planSummaryModal.type = 'summary';
    this.store.planSummaryModal.title = getLabel('509021', '总结');
    this.store.planSummaryModal.planSummaryModalVisible = true;
    this.store.planSummaryModal.edit = false;
    this.store.planSummaryModal.rowIndex = -1;
    return datas;
  };

  openAdd = (rowIndex) => {
    this.store.planSummaryModal.type = 'summary';
    this.store.planSummaryModal.title = getLabel('509021', '总结');
    this.store.planSummaryModal.planSummaryModalVisible = true;
    this.store.planSummaryModal.edit = false;
    this.store.planSummaryModal.rowIndex = rowIndex;
  };

  willDelete = (datas, keys) => {
    this.store.resData.summaryout = datas;
    return true;
  };


  richTextChange = v => {
    let { planReportViewStore } = this.props;
    // planReportViewStore.resData.remark=v
    planReportViewStore.onInputValueChange('richTextValue', v);
  };



  getTableProps = () => {
    const { summarymap } = this.store.resData

    let _this = this;
    let columns = toJS(this.store.summaryinColumns)
    let tableProps = {
      onRowClick: (...arg) => {
        if (_this.canEditPlan()) {
          _this.store.planSummaryModal.type = 'summary';
          _this.store.planSummaryModal.title = getLabel('84011', '工作总结');
          _this.store.planSummaryModal.editData = arg[0];
          _this.store.planSummaryModal.planSummaryModalVisible = true;
          _this.store.planSummaryModal.edit = true;
        }
      },
    }
    tableProps.scroll = { x: summarymap.totalwidth + '%' }

    return tableProps;
  };
  //查看明细 弹出明细弹窗
  viewDetail(e, text, record, index, onEdit, dataType, inOrOut) {
    e.stopPropagation();
    let { category, resourceid, summaryin, summaryout, planstatus } = this.store.resData;

    let canedit = this.store.buttonAuth.edit;
    delete record.fbdate;
    if (record.id.indexOf('temp') != -1) {
      record.id = '';
    }
    let _this = this;
    let detailData = '[' + JSON.stringify(record) + ']';
    //先保存 再查看
    this.store.saveDetailView({
      operation: 'save_detail',
      resourceid: resourceid,
      plandetailid: record.id,
      dataType: dataType,
      detailData: detailData,
      type1: _this.store.tabSelectKey,
      //保存成功后回调
      doback: function (detailid) {
        if (inOrOut == 'in') {
          summaryin[index].id = detailid
        } else {
          summaryout[index].id = detailid
        }

        _this.setState({
          detailContent: (
            <PlanDetail ecId={`${this && this.props && this.props.ecId || ''}_PlanDetail@n9nx8e`}
              refreshMark={new Date().getTime()} //刷新标识
              detailid={detailid} //detailid
              category={category} //文档目录
              datatype={dataType}//数据类型
              inOrOut={inOrOut} //计划内还是外
              canedit={canedit}//是否能编辑
              resourceid={resourceid} //人员id
              visible={true} //是否可见
              rowIndex={index}//行index 
              onClose={_this.closeDia}
              type={'report'}
              planstatus={planstatus}
            />
          ),
        });
      },
    });
  }

  //回调关闭dialog
  closeDia = (params, detailid) => {
    params['viewdate'] = ''
    delete params['viewdate']
    this.setState({ detailContent: '' });
    if (params) {
      let { summaryin, summaryout } = this.store.resData;
      let thisRow = {}
      let rowIndex = -1
      //根据detailid找出是计划内还是计划外的，然后把赋值
      summaryin.map((v, i) => {
        if (v.id == detailid) {
          thisRow = v
          rowIndex = i
        }
      })
      if (rowIndex > -1) {
        for (let k in params) {
          if(k && !k.startsWith("s_")){
            if(params[k]){
              thisRow[k] =  params[k]
              if(!k.startsWith("s_")){
                thisRow["s_"+k] =  typeof(thisRow[k])=='string'? thisRow[k].replace(/\n/g, "<br/>"):thisRow[k]
              }
          }else{
            thisRow[k] = ''
            if(!k.startsWith("s_")){
              thisRow["s_"+k]=''
            }
          }
          }

        }
        thisRow["id"] = detailid
        summaryin[rowIndex] = thisRow
      } else {
        summaryout.map((v, i) => {
          if (v.id == detailid) {
            thisRow = v
            rowIndex = i
          }
        })

        for (let k in params) {
          if(k && !k.startsWith("s_")){
            if(params[k]){
              thisRow[k] =  params[k]
              if(!k.startsWith("s_")){
                thisRow["s_"+k] =  typeof(thisRow[k])=='string'? thisRow[k].replace(/\n/g, "<br/>"):thisRow[k]
              }
          }else{
            thisRow[k] = ''
            if(!k.startsWith("s_")){
              thisRow["s_"+k]=''
            }
          }
          }

        }
        thisRow["id"] = detailid
        summaryout[rowIndex] = thisRow
      }

    }
    //this.store.getPlanDetail ();
  };
  addToPlanList = record => {
    record.id = 'temp' + new Date().getTime();

    this.store.resData.planlist.push(record);
    message.success(getLabel('30700', '操作成功'));
  };

  //创建任务
  createTask(e, text, record, index, onEdit, dataType, inOrOut) {
    e.stopPropagation();
    if (record.name == undefined || record.name.length == 0) {
      Modal.warning({
        title: getLabel('558', '提示'),
        content: getLabel('509022', '请填写标题!'),
      });
      return;
    }
    let _this = this;
    let { resourceid, summaryin, summaryout } = this.store.resData;
    Modal.confirm({
      title: getLabel('131329', '信息确认'),
      content: getLabel('509023', '确定创建任务？'),
      onOk() {
        let param = {};
        param.taskName = record.name;
        param.principalid = _this.store.resData.resourceid;
        param.begindate = record.begindate2 ? record.begindate2 : record.begindate1;
        param.enddate = record.enddate2 ? record.enddate2 : record.enddate1;
        delete record.fbdate;
        if (record.id.indexOf('temp') != -1) {
          record.id = '';
        }
        let detailData = '[' + JSON.stringify(record) + ']';
        if (record.id == '') {
          //先保存 再查看
          _this.store.saveDetailView({
            operation: 'save_detail',
            resourceid: resourceid,
            plandetailid: record.id,
            dataType: dataType,
            detailData: detailData,
            type1: _this.store.tabSelectKey,

            //保存成功后回调
            doback: function (detailid) {
              //设置id 
              if (inOrOut == 'in') {
                summaryin[index].id = detailid
              } else {
                summaryout[index].id = detailid
              }

              record.id = detailid
              param.plandetailid = detailid;
              _this.store.addTask(param,inOrOut == 'in'?  summaryin[index]:summaryout[index]);
            },
          });
        } else {
          param.plandetailid = record.id;
          _this.store.addTask(param,inOrOut == 'in'?  summaryin[index]:summaryout[index]);

        }

      },
      onCancel() { },
    });
  }

  //第二个参数是类型 type in 是 计划内 out 计划外
  addOperationColumns = (columns, type) => {
    let { planstatus } = this.store.resData;
    columns.push({
      title: <span />,
      dataIndex: 'customrender',
      width: '0',
      key: 'customrender',
      com: [
        {
          type: 'CUSTOM',
          key: 'customrender',
          render: (text, record, index, onEdit) => (
            <div className="operation-col">
              <div className='icon-context'>
                {this.canEditPlan() &&
                  <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@3pdzgd@${index}`} title={getLabel('509024', '添加到工作计划')}>
                    <span>
                      <i
                        className="icon-coms-down"
                        onClick={e => {
                          e.stopPropagation();
                          this.addToPlanList(record);
                        }}
                      />{' '}
                    </span>
                  </Tooltip>}
                {this.canEditPlan() &&
                  type == 'out' &&
                  <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@s4b3nq@${index}`} title={getLabel('509025', '新增一行数据')}>
                    <span>
                      <i
                        className="icon-coms-Left"
                        onClick={e => {
                          e.stopPropagation();
                          this.openAdd(index);
                        }}
                      />{' '}
                    </span>
                  </Tooltip>}
                {this.store.resData.createtask &&
                  <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@lto65e@${index}`} title={getLabel('16336', '创建任务')}>
                    <span>
                      <i
                        className="icon-coms-plus"
                        onClick={e =>
                          this.createTask(
                            e,
                            text,
                            record,
                            index,
                            onEdit,
                            '3',
                            type
                          )}
                      />
                      {' '}
                    </span>
                  </Tooltip>}
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@uth4yg@${index}`} title={getLabel('382624', '查看明细')}>
                  <span>
                    <i
                      className="icon-coms-form-copy"
                      onClick={e =>
                        this.viewDetail(
                          e,
                          text,
                          record,
                          index,
                          onEdit,
                          '3',
                          type
                        )}
                    />
                    {' '}
                  </span>
                </Tooltip>
              </div>
            </div>
          ),
        },
      ],
      render: (text, record, index, onEdit) => (
        <div className="operation-col">
          <div className='icon-context'>
            {this.canEditPlan() &&
              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@rp3t78@${index}`} title={getLabel('509024', '添加到工作计划')}>
                <span>
                  <i
                    className="icon-coms-down"
                    onClick={e => {
                      e.stopPropagation();
                      this.addToPlanList(record);
                    }}
                  />{' '}
                </span>
              </Tooltip>}
            {this.canEditPlan() &&
              type == 'out' &&
              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@rbcmq6@${index}`} title={getLabel('509025', '新增一行数据')}>
                <span>
                  <i
                    className="icon-coms-Left"
                    onClick={e => {
                      e.stopPropagation();
                      this.openAdd(index);
                    }}
                  />{' '}
                </span>
              </Tooltip>}
            {this.store.resData.createtask &&
              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@tva7b1@${index}`} title={getLabel('16336', '创建任务')}>
                <span>
                  <i
                    className="icon-coms-plus"
                    onClick={e =>
                      this.createTask(
                        e,
                        text,
                        record,
                        index,
                        onEdit,
                        '3',
                        type
                      )}
                  />
                  {' '}
                </span>
              </Tooltip>}
            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@kgm5mp@${index}`} title={getLabel('382624', '查看明细')}>
              <span>
                <i
                  className="icon-coms-form-copy"
                  onClick={e =>
                    this.viewDetail(
                      e,
                      text,
                      record,
                      index,
                      onEdit,
                      "3",
                      type
                    )}
                />
                {' '}
              </span>
            </Tooltip>
          </div>
        </div>
      ),
    });
  };

  canEditPlan = () => {
    return this.store.buttonAuth.edit;
  };
  deepCopy = obj => {
    var result = Array.isArray(obj) ? [] : {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          result[key] = this.deepCopy(obj[key]); //递归复制
        } else {
          result[key] = obj[key];
        }
      }
    }
    return result;
  };

  //计划内变化事件  主要检查日期
  onSummaryInChange = (datas) => {

    let days = 0;
    let flag = true;
    let col = '';
    let tip = '';

    datas.some((d, i) => {
      if (d["begindate2"] && d['enddate2'] && d['enddate2'] != '') {
        days = Util.DateDiffDays(d["begindate2"], d['enddate2']);
        if (days < 0) {
          flag = false;
          tip = getLabel('509026', '实际开始日期不能大于实际结束日期!');
        } else {
          col = 'days2';
        }
      } else if (
        d['enddate2'] &&
        d['begindate2'] &&
        d['begindate2'] != ''
      ) {
        days = Util.DateDiffDays(d['enddate2'], d['begindate2']);
        if (days < 0) {
          flag = false;
          tip = getLabel('509027', '实际结束日期不能小于实际开始日期!');
        } else {
          col = 'days2';
        }
      } else if (
        d['begindate1'] &&
        d['enddate1'] &&
        d['enddate1'] != ''
      ) {
        days = Util.DateDiffDays(d['begindate1'], d['enddate1']);
        if (days < 0) {
          flag = false;
          tip = getLabel('509028', '计划开始日期不能大于计划结束日期!');
        } else {
          col = 'days1';
        }
      } else if (
        d['enddate1'] &&
        d['begindate1'] &&
        d['begindate1'] != ''
      ) {
        days = Util.DateDiffDays(d['enddate1'], d['begindate1']);
        if (days < 0) {
          flag = false;
          tip = getLabel('509029', '计划结束日期不能小于计划开始日期!');
        } else {
          col = 'days1';
        }

      }
      if (col != '' && days >= 0) {
        //this.store.resData.summaryin[i][col] = days;
        d[col] = days
        d['s_'+col] = days
      }
      if (!flag) {
        message.info(tip);

        return true;//跳出循环
      }
      col = ""

    })
    if (flag) {
      this.store.resData.summaryin = datas
    }

  };

  getSummaryInTableConfig = () => {
    const { summarymap } = this.store.resData

    let columns = toJS(this.store.summaryinColumns)
    this.addOperationColumns(columns, 'in')
    let columnConfig = {
      columns,
      pagination: false,
      dataSource: toJS(this.store.resData.summaryin),
      className: 'wea-workrelate-antd-table',
      showEmptyText: true,
      scroll: {
        x: summarymap.totalwidth + "%"
      }
    }

    return columnConfig
  }

  render() {
    let { planReportViewStore } = this.props;
    let {
      dateSelect,
      tabSelectKey,
      summaryinColumns,
      summaryColumns,
      resData,
    } = planReportViewStore;
    resData = toJS(resData);
    dateSelect = toJS(dateSelect);
    if (dateSelect.month.length < 2) {
      dateSelect.month = "0" + dateSelect.month
    }
    summaryColumns = toJS(summaryColumns);
    summaryinColumns = toJS(summaryinColumns)
    let { summaryout, remark } = resData;
    let canedit = this.store.buttonAuth.edit;
    this.addOperationColumns(summaryColumns, 'out');
    this.addOperationColumns(summaryinColumns, 'in');

    let borderMonthTitle = getUserLanguage() == 8 ?
      `${dateSelect.year}-${dateSelect.month} work summary`
      :
      `${dateSelect.year}${getLabel('26577', '年')}${dateSelect.month}${getLabel('509037', '月工作总结')} `

    let borderWeekTitle = getUserLanguage() == 8 ?
      `${dateSelect.year} Week ${dateSelect.week} work summary`
      :
      `${dateSelect.year}${getLabel('26577', '年')}${dateSelect.week}${getLabel('509038', '周工作总结')} `




    return (
      <div className="last-month">
        <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@v852rd`}
          title={
            tabSelectKey == '1'
              ? <div>
                <i
                  className="icon-coms-mulujibenxinxi"
                  style={{ color: 'green' }}
                />
                {' '}
                {borderMonthTitle}
              </div>
              : <div>
                <i
                  className="icon-coms-mulujibenxinxi"
                  style={{ color: 'green' }}
                />
                {' '}
                {borderWeekTitle}
              </div>
          }
        >
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@sf06gh`}
            title={
              <div>
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@99yj4o`} title={getLabel('509031', '【计划内】工作来源于上一周期的计划，如有其它工作可在【计划外】中添加')}>
                  <span>{getLabel('509032', '计划内')}</span>
                </Tooltip>
              </div>
            }
            showGroup={true}
            className="search-group"
          >
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ezbaqr`} {...this.getSummaryInTableConfig()} />
          </WeaSearchGroup>
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@u1n9mu`}
            title={
              <div>
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@lvzk2a`} title={getLabel('509033', '【计划外】工作表示不属于上一周期计划中的工作内容')}>
                  <span>{getLabel('509034', '计划外')}</span>
                </Tooltip>
                {/* <span className='edit-tip' style={{display:this.store.authority.canedit?"inline":'none'}}>{getLabel('509035','点击内容进行编辑')}</span> */}
              </div>
            }
            showGroup={true}
            className="search-group"
          >
            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@htm84j`}
              // showTitle={true}
              showCopy={false}
              draggable={false}
              pushTitleIntoHeader={false}
              columns={summaryColumns}
              buttonsType="inline"
              datas={summaryout}
              willAdd={this.willAdd}
              willDelete={this.willDelete}
              tableProps={this.getTableProps()}
              showAdd={this.canEditPlan()}
              showDelete={this.canEditPlan()}
              getRowSelection={rowSelection => {
                return !canedit ? false : rowSelection;
              }}
            />
          </WeaSearchGroup>
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@q5hh82`}
            title={getLabel('25734', '说明')}
            showGroup={true}
            className="search-group"
          >

            {this.canEditPlan()
              ? <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@ybp4zz`}
                ckConfig={{
                  startupFocus: false,
                  toolbar: [
                    { name: 'document', items: ['Source'] },
                    { name: 'clipboard', items: ['Undo', 'Redo'] },
                    { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
                    { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                    { name: 'colors', items: ['TextColor'] },
                    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
                    { name: 'insert', items: ['Image', 'Flash', 'Table', 'Smiley'] },
                    { name: 'tools', items: ['Maximize'] },
                  ],
                  height: 200,
                  autoGrow_minHeight: 200,
                  autoGrow_maxHeight: 200,
                  uploadUrl: '/api/doc/upload/uploadFile',
                  resize_enabled: false,
                }}
                value={remark}
                // extentsConfig
                onChange={v => this.richTextChange(v)}
                onToolsChange={(name, ids, list, type) =>
                  Util.transfStr(name, ids, list, type)}
              />
              : <div
                style={{ padding: '10px' }}
                dangerouslySetInnerHTML={{ __html: remark }}
              />}

          </WeaSearchGroup>
        </SearchGroupBorderLeft>
        {this.state.detailContent}
      </div>
    );
  }
}
